package com.then.libary.thread;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import com.google.zxing.oned.rss.FinderPattern;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

public class ThreadPoolSingle implements Runnable {
	private ReadWriteLock myLock = new ReentrantReadWriteLock();;
	Lock readLock;
	Lock writeLock;
	private Handler handler;
	private Handler outerHandler;
	private LinkedList<ThreadTask> list = new LinkedList<ThreadPoolSingle.ThreadTask>();

	public ThreadPoolSingle(Handler outerHandler) {
		// TODO Auto-generated constructor stub
		Executors.newSingleThreadExecutor();
		this.outerHandler = outerHandler;
		writeLock = myLock.writeLock();
		readLock = myLock.readLock();

	}

	public class ThreadTask {
		private Map<String, String> dataMap;
		private int taskId;
		private boolean finshed;

		public ThreadTask(int taskId) {
			this.taskId = taskId;
			dataMap = new HashMap<String, String>();
		}

		public void put(String key, String value) {
			dataMap.put(key, value);
		}

		@Override
		public String toString() {
			return "ThreadTask [taskId=" + taskId + "]";
		}

		public boolean isFinshed() {
			return finshed;
		}

		public int getid() {
			return taskId;
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		Looper.prepare();
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub

				ThreadTask threadTask = getNowTask();
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				outerHandler.obtainMessage(11, threadTask.getid(), 1);
			}
		};
		Looper.loop();
	}

	public ThreadTask getNowTask() {
		readLock.lock();
		ThreadTask task = null;
		try {
			task = list.poll();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			readLock.unlock();
			return task;

		}

	}

	public void add(ThreadTask task) {
		writeLock.lock();
		try {
			boolean flag = false;
			if (list.contains(task)) {
				list.remove(task);
				flag = true;

			}
			if (!flag) {
				list.addFirst(task);
				handler.sendEmptyMessage(1);
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			writeLock.unlock();
		}

	}

}
